package me.xiaosiqi.syt.hosp.service.impl;

import me.xiaosiqi.syt.hosp.repository.DepartmentRepository;
import me.xiaosiqi.syt.hosp.repository.HospitalRepository;
import me.xiaosiqi.syt.hosp.service.DepartmentService;
import me.xiaosiqi.syt.model.hosp.Department;
import me.xiaosiqi.syt.model.hosp.Hospital;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: xiaosiqi
 * @date:2022/7/31 18:07
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Department department) {
        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (null != departmentExist) {
            department.setId(departmentExist.getId());
            department.setCreateTime(departmentExist.getCreateTime());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department>  departmentList(String hoscode, Integer page, Integer limit) {
        Pageable pageable = PageRequest.of(page-1,limit);

        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                        .withIgnoreCase(true);
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department,matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public void departmentRemove(String hoscode,String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (null != department){
            departmentRepository.deleteById(department.getId());
        }
    }
}
